package com.zk.zookeeper01;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;

public class TestZookeeper {

    // zookeeper连接地址,中间不要有空格
    private String connectString = "192.168.189.150:2181,192.168.189.151:2181,192.168.189.152:2181";

    // 连接超时时间2000毫秒
    private int sessionTimeOut = 2000;

    private ZooKeeper zkClient;

    /**
     * 对应操作的zookeeper版本是3.4.10
     */
    //此处是连接zookeeper集群
    @Before
    public void init() throws IOException {

        zkClient = new ZooKeeper(connectString, sessionTimeOut, new Watcher() {
            @Override
            public void process(WatchedEvent watchedEvent) {
                //收到时间通知后的回调函数(用户的业务逻辑)
                System.out.println(watchedEvent.getType() + "--" + watchedEvent.getPath());
//                再次监听
                try {
                    zkClient.getChildren("/", true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }


    //1.创建节点
    @Test
    public void createNode() {

//        ZooDefs.Ids.OPEN_ACL_UNSAFE:权限控制OPEN_ACL_UNSAFE最常用
//        有四种类型的znode：
//
        //PERSISTENT-持久化目录节点
        //客户端与zookeeper断开连接后，该节点依旧存在
        //PERSISTENT_SEQUENTIAL-持久化顺序编号目录节点
        //客户端与zookeeper断开连接后，该节点依旧存在，只是Zookeeper给该节点名称进行顺序编号
        //EPHEMERAL-临时目录节点
        //客户端与zookeeper断开连接后，该节点被删除
        //EPHEMERAL_SEQUENTIAL-临时顺序编号目录节点
        //客户端与zookeeper断开连接后，该节点被删除，只是Zookeeper给该节点名称进行顺序编号
        try {
            String path = zkClient.create("/atguigu", "dashuju".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            System.out.println(path);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    //2.获取子节点并监听节点变化
    @Test
    public void getChildren() {
        try {
            List<String> children = zkClient.getChildren("/", true);
            children.forEach(System.out::println);
            Thread.sleep(Long.MAX_VALUE);
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //3.判断Znode是否存在
    @Test
    public void exist() {
        try {
            Stat stat = zkClient.exists("/china", false);
            System.out.println(stat == null ? "not exist" : "exist");
        } catch (KeeperException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
